<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>迭代器模式 | Freeisms</title>
    <meta name="generator" content="VuePress 1.7.1">
    <link rel="icon" href="/favicon.ico">
    <link rel="manifest" href="/manifest.json">
    <link rel="apple-touch-icon" href="/apple-touch-icon.png">
    <meta name="description" content="记录个人前端技术成长点滴">
    <meta name="theme-color" content="#3eaf7c">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    
    <link rel="preload" href="/assets/css/0.styles.9efbc543.css" as="style"><link rel="preload" href="/assets/js/app.e45e7f79.js" as="script"><link rel="preload" href="/assets/js/4.1dc261f9.js" as="script"><link rel="preload" href="/assets/js/24.df877caa.js" as="script"><link rel="prefetch" href="/assets/js/10.910e44c4.js"><link rel="prefetch" href="/assets/js/11.3cb7fbc0.js"><link rel="prefetch" href="/assets/js/12.e84e4441.js"><link rel="prefetch" href="/assets/js/13.a20b1e0e.js"><link rel="prefetch" href="/assets/js/14.5bb81eb0.js"><link rel="prefetch" href="/assets/js/15.9ac9c7b5.js"><link rel="prefetch" href="/assets/js/16.e65d6e8b.js"><link rel="prefetch" href="/assets/js/17.3bcb37e9.js"><link rel="prefetch" href="/assets/js/18.238c27dc.js"><link rel="prefetch" href="/assets/js/19.0bf085fb.js"><link rel="prefetch" href="/assets/js/20.af32ca4b.js"><link rel="prefetch" href="/assets/js/21.d7d0a4bf.js"><link rel="prefetch" href="/assets/js/22.fb0bd41c.js"><link rel="prefetch" href="/assets/js/23.e40c513c.js"><link rel="prefetch" href="/assets/js/25.ff943ee7.js"><link rel="prefetch" href="/assets/js/26.6975fab4.js"><link rel="prefetch" href="/assets/js/27.49355cdd.js"><link rel="prefetch" href="/assets/js/28.08ac8c0a.js"><link rel="prefetch" href="/assets/js/29.864244b6.js"><link rel="prefetch" href="/assets/js/30.9fde9cc1.js"><link rel="prefetch" href="/assets/js/31.04c169d6.js"><link rel="prefetch" href="/assets/js/32.57021f58.js"><link rel="prefetch" href="/assets/js/33.09502731.js"><link rel="prefetch" href="/assets/js/34.8a018286.js"><link rel="prefetch" href="/assets/js/35.097f93be.js"><link rel="prefetch" href="/assets/js/36.37ccdfeb.js"><link rel="prefetch" href="/assets/js/37.11976f3e.js"><link rel="prefetch" href="/assets/js/38.98243aad.js"><link rel="prefetch" href="/assets/js/39.a3c78447.js"><link rel="prefetch" href="/assets/js/40.7be6398d.js"><link rel="prefetch" href="/assets/js/41.33d492ee.js"><link rel="prefetch" href="/assets/js/42.f1c675e6.js"><link rel="prefetch" href="/assets/js/43.bbda546b.js"><link rel="prefetch" href="/assets/js/44.2dc401cd.js"><link rel="prefetch" href="/assets/js/45.33bd1151.js"><link rel="prefetch" href="/assets/js/46.b6b09012.js"><link rel="prefetch" href="/assets/js/47.55feb448.js"><link rel="prefetch" href="/assets/js/48.fc9dc909.js"><link rel="prefetch" href="/assets/js/49.fd6d33c4.js"><link rel="prefetch" href="/assets/js/5.ac586c16.js"><link rel="prefetch" href="/assets/js/50.8e33b7f9.js"><link rel="prefetch" href="/assets/js/51.fd278c0a.js"><link rel="prefetch" href="/assets/js/52.fbd66a3b.js"><link rel="prefetch" href="/assets/js/53.f829ac68.js"><link rel="prefetch" href="/assets/js/54.7c7e5ec8.js"><link rel="prefetch" href="/assets/js/55.42e87201.js"><link rel="prefetch" href="/assets/js/56.2301ffbd.js"><link rel="prefetch" href="/assets/js/57.6d5ed1a9.js"><link rel="prefetch" href="/assets/js/58.8dc29eab.js"><link rel="prefetch" href="/assets/js/59.722945c8.js"><link rel="prefetch" href="/assets/js/6.64876e20.js"><link rel="prefetch" href="/assets/js/60.c43354e4.js"><link rel="prefetch" href="/assets/js/61.b9d1ad1d.js"><link rel="prefetch" href="/assets/js/62.d61bfc10.js"><link rel="prefetch" href="/assets/js/63.d84a88b5.js"><link rel="prefetch" href="/assets/js/64.0f25c14d.js"><link rel="prefetch" href="/assets/js/7.d74ac93a.js"><link rel="prefetch" href="/assets/js/8.6c8e2482.js"><link rel="prefetch" href="/assets/js/9.085dc649.js"><link rel="prefetch" href="/assets/js/vendors~flowchart.4e554982.js"><link rel="prefetch" href="/assets/js/vendors~notification.4b668bb8.js">
    <link rel="stylesheet" href="/assets/css/0.styles.9efbc543.css">
  </head>
  <body>
    <div id="app" data-server-rendered="true"><div class="theme-container"><header class="navbar"><div class="sidebar-button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" role="img" viewBox="0 0 448 512" class="icon"><path fill="currentColor" d="M436 124H12c-6.627 0-12-5.373-12-12V80c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12z"></path></svg></div> <a href="/" class="home-link router-link-active"><!----> <span class="site-name">Freeisms</span></a> <div class="links"><div class="search-box"><input aria-label="Search" autocomplete="off" spellcheck="false" value=""> <!----></div> <nav class="nav-links can-hide"><div class="nav-item"><a href="/my-docs/js/" class="nav-link">
  JavaScript
</a></div><div class="nav-item"><a href="/my-docs/design-pattern/" class="nav-link router-link-active">
  设计模式
</a></div><div class="nav-item"><a href="/my-docs/leetcode/" class="nav-link">
  LeetCode
</a></div><div class="nav-item"><a href="/my-docs/library/vue-juejin-comment.html" class="nav-link">
  开源库
</a></div><div class="nav-item"><a href="https://www.striveforus.com/" target="_blank" rel="noopener noreferrer" class="nav-link external">
  博客
  <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></div> <a href="https://github.com/Fengfengfeng-up/personal-docs" target="_blank" rel="noopener noreferrer" class="repo-link">
    GitHub
    <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></nav></div></header> <div class="sidebar-mask"></div> <aside class="sidebar"><nav class="nav-links"><div class="nav-item"><a href="/my-docs/js/" class="nav-link">
  JavaScript
</a></div><div class="nav-item"><a href="/my-docs/design-pattern/" class="nav-link router-link-active">
  设计模式
</a></div><div class="nav-item"><a href="/my-docs/leetcode/" class="nav-link">
  LeetCode
</a></div><div class="nav-item"><a href="/my-docs/library/vue-juejin-comment.html" class="nav-link">
  开源库
</a></div><div class="nav-item"><a href="https://www.striveforus.com/" target="_blank" rel="noopener noreferrer" class="nav-link external">
  博客
  <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></div> <a href="https://github.com/Fengfengfeng-up/personal-docs" target="_blank" rel="noopener noreferrer" class="repo-link">
    GitHub
    <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></nav>  <ul class="sidebar-links"><li><section class="sidebar-group depth-0"><p class="sidebar-heading open"><span>设计模式</span> <!----></p> <ul class="sidebar-links sidebar-group-items"><li><a href="/my-docs/design-pattern/" aria-current="page" class="sidebar-link">写在前面</a></li><li><a href="/my-docs/design-pattern/singleton.html" class="sidebar-link">单例模式</a></li><li><a href="/my-docs/design-pattern/strategy.html" class="sidebar-link">策略模式</a></li><li><a href="/my-docs/design-pattern/proxy.html" class="sidebar-link">代理模式</a></li><li><a href="/my-docs/design-pattern/iterator.html" aria-current="page" class="active sidebar-link">迭代器模式</a><ul class="sidebar-sub-headers"><li class="sidebar-sub-header"><a href="/my-docs/design-pattern/iterator.html#理解迭代" class="sidebar-link">理解迭代</a></li><li class="sidebar-sub-header"><a href="/my-docs/design-pattern/iterator.html#内部迭代器和外部迭代器" class="sidebar-link">内部迭代器和外部迭代器</a></li></ul></li><li><a href="/my-docs/design-pattern/pub-sub.html" class="sidebar-link">发布—订阅模式</a></li><li><a href="/my-docs/design-pattern/command.html" class="sidebar-link">命令模式</a></li><li><a href="/my-docs/design-pattern/composite.html" class="sidebar-link">组合模式</a></li><li><a href="/my-docs/design-pattern/template-method.html" class="sidebar-link">模板方法模式</a></li></ul></section></li></ul> </aside> <main class="page"> <div class="theme-default-content content__default"><h1 id="迭代器模式"><a href="#迭代器模式" class="header-anchor">#</a> 迭代器模式</h1> <p><strong>迭代器模式</strong>是指提供一种方法顺序访问一个聚合对象中的各个元素，而又不需要暴露该对象的内部表示。</p> <p>迭代器模式可以把迭代的过程从业务逻辑中分离出来，在使用迭代器模式之后，即使不关心对象的内部构造，也可以按顺序访问其中的每个元素。</p> <h2 id="理解迭代"><a href="#理解迭代" class="header-anchor">#</a> 理解迭代</h2> <p>循环是迭代机制的基础，这是因为它可以指定迭代的次数，以及每次迭代要执行什么操作。每次循环都会在下一次迭代开始之前完成，而每次迭代的顺序都是事先定义好的。例如遍历一个数组：</p> <div class="language-js extra-class"><pre class="language-js"><code><span class="token keyword">const</span> arr <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token string">'bar'</span><span class="token punctuation">,</span> <span class="token string">'foo'</span><span class="token punctuation">,</span> <span class="token string">'baz'</span><span class="token punctuation">]</span>

<span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">let</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> arr<span class="token punctuation">.</span>length<span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>arr<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>
<span class="token comment">// bar</span>
<span class="token comment">// foo</span>
<span class="token comment">// baz</span>
</code></pre></div><p>通过这种循环操作来执行例程有以下不足：</p> <ul><li>迭代之前需要事先知道如何使用数据结构。数组中的每一项都只能先通过引用取得数组对象，然后再通过 <code>[]</code> 操作符取得特定索引位置上的项。这种情况并不适用于所有数据结构，例如 <a href="https://developer.mozilla.org/zh-cn/docs/Web/JavaScript/Reference/Global_Objects/Map" target="_blank" rel="noopener noreferrer">Map<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>。</li> <li>遍历顺序并不是数据结构固有的。通过递增索引来访问数据是特定于数组类型的方式，并不适用于其他具有隐式顺序的数据结构。</li></ul> <p>为此，很多语言都提供了原生语言结构以解决这个问题，开发者无须事先知道如何迭代就能实现迭代操作。这个解决方案就是迭代器模式。Python、Java、C++，还有其他很多语言都对迭代器模式提供了完备的支持。</p> <p>JavaScript 在 ES5 新增了 <code>Array.prototype.forEach()</code> 方法，它解决了单独记录索引和通过数组对象取得值的问题，但是没有办法标识迭代何时终止。ES6 以后，JavaScript 新增了<a href="https://developer.mozilla.org/zh-cn/docs/Web/JavaScript/Guide/Iterators_and_Generators#%E8%BF%AD%E4%BB%A3%E5%99%A8" target="_blank" rel="noopener noreferrer">迭代器和生成器<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>，完美地支持了迭代器模式。</p> <h2 id="内部迭代器和外部迭代器"><a href="#内部迭代器和外部迭代器" class="header-anchor">#</a> 内部迭代器和外部迭代器</h2> <h3 id="内部迭代器"><a href="#内部迭代器" class="header-anchor">#</a> 内部迭代器</h3> <p>由于内部迭代器的迭代规则在使用前就被定义，所以在调用的时候比较方便，外界不用关心迭代器内部的实现，正因为如此，内部迭代器也不够灵活。</p> <p>比如实现一个简单迭代器 <code>each()</code> 如下：</p> <div class="language-js extra-class"><pre class="language-js"><code><span class="token keyword">const</span> <span class="token function-variable function">each</span> <span class="token operator">=</span> <span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token parameter">arr<span class="token punctuation">,</span> fn</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">let</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> arr<span class="token punctuation">.</span>length<span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token function">fn</span><span class="token punctuation">.</span><span class="token function">call</span><span class="token punctuation">(</span>arr<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">,</span> arr<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">,</span> i<span class="token punctuation">)</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div><p>显然， <code>each()</code> 函数将无法完成同时迭代两个数组的需求，如果迭代的对象不是数组结构也会失败。</p> <h3 id="外部迭代器"><a href="#外部迭代器" class="header-anchor">#</a> 外部迭代器</h3> <p>外部迭代器必须显式地请求迭代下一个元素，虽然增加了一些调用的复杂度，但增强了其灵活性，使用者可以手动控制迭代的过程。</p> <p>比如实现一个外部迭代器工厂 <code>Iterator()</code>，它返回一个迭代器对象：</p> <div class="language-js extra-class"><pre class="language-js"><code><span class="token keyword">const</span> <span class="token function-variable function">Iterator</span> <span class="token operator">=</span> <span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token parameter">obj</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">let</span> index <span class="token operator">=</span> <span class="token number">0</span>
  <span class="token keyword">let</span> done <span class="token operator">=</span> <span class="token boolean">false</span>

  <span class="token keyword">const</span> <span class="token function-variable function">next</span> <span class="token operator">=</span> <span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    done <span class="token operator">=</span> index <span class="token operator">&gt;=</span> obj<span class="token punctuation">.</span>length
    <span class="token keyword">const</span> value <span class="token operator">=</span> done <span class="token operator">?</span> <span class="token keyword">undefined</span> <span class="token operator">:</span> obj<span class="token punctuation">[</span>index<span class="token operator">++</span><span class="token punctuation">]</span>
    <span class="token keyword">return</span> <span class="token punctuation">{</span> done<span class="token punctuation">,</span> value <span class="token punctuation">}</span>
  <span class="token punctuation">}</span>

  <span class="token keyword">return</span> <span class="token punctuation">{</span>
    next
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>

<span class="token keyword">const</span> iterator <span class="token operator">=</span> <span class="token function">Iterator</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token string">'foo'</span><span class="token punctuation">,</span> <span class="token string">'bar'</span><span class="token punctuation">,</span> <span class="token string">'baz'</span><span class="token punctuation">]</span><span class="token punctuation">)</span>
console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>iterator<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token comment">// {done: false, value: &quot;foo&quot;}</span>
console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>iterator<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token comment">// {done: false, value: &quot;bar&quot;}</span>
console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>iterator<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token comment">// {done: false, value: &quot;baz&quot;}</span>
console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>iterator<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token comment">// {done: true, value: undefined}</span>
</code></pre></div><p>外部迭代器虽然调用方式相对复杂，但它可以满足更多场景。</p></div> <footer class="page-edit"><div class="edit-link"><a href="https://github.com/Fengfengfeng-up/personal-docs/edit/main/docs/my-docs/design-pattern/iterator.md" target="_blank" rel="noopener noreferrer">在 GitHub 上编辑此页</a> <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></div> <div class="last-updated"><span class="prefix">上次更新:</span> <span class="time">3/3/2021, 1:42:33 PM</span></div></footer> <div class="page-nav"><p class="inner"><span class="prev">
      ←
      <a href="/my-docs/design-pattern/proxy.html" class="prev">
        代理模式
      </a></span> <span class="next"><a href="/my-docs/design-pattern/pub-sub.html">
        发布—订阅模式
      </a>
      →
    </span></p></div> </main></div><div class="global-ui"><!----></div></div>
    <script src="/assets/js/app.e45e7f79.js" defer></script><script src="/assets/js/4.1dc261f9.js" defer></script><script src="/assets/js/24.df877caa.js" defer></script>
  </body>
</html>
